package com.hu.auth.common.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 生成JSON Web令牌的工具类
 */
public class JwtUtil {

    //token过期时间
    private static final long tokenExpiration = 24 * 60 * 60 * 1000;
    //加密秘钥
    private static final String tokenSignKey = "123456";

    //根据用户id生成token字符串
    // public static String createToken(Long userId, String userPerms) {
    //     return Jwts.builder()
    //             .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
    //             .claim("userId", userId)
    //             .claim("userPerms", userPerms)
    //             .signWith(SignatureAlgorithm.HS512, tokenSignKey)
    //             .compressWith(CompressionCodecs.GZIP)
    //             .compact();
    // }

    public static String createToken(Long userId) {
        return Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    // 验证token
    public static boolean verifyToken(String token) {
        try {
            Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //从token字符串获取userid
    public static Long getUserId(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return Long.valueOf(claims.get("userId").toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //从token字符串获取权限
    // public static String getUserPerms(String token) {
    //     if (StringUtils.isEmpty(token)) {
    //         return null;
    //     }
    //     try {
    //         Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
    //         Claims claims = claimsJws.getBody();
    //         return (String) claims.get("userPerms");
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //         return null;
    //     }
    // }

    public static void main(String[] args) {
        String token = JwtUtil.createToken(1L);
        System.out.println(JwtUtil.verifyToken(token));
        System.out.println(JwtUtil.getUserId(token));
    }
}